package nbcp.db.redis.proxy

import io.lettuce.core.RedisClient
import io.lettuce.core.api.sync.RedisCommands
import io.lettuce.core.codec.ByteArrayCodec
import io.lettuce.core.codec.RedisCodec
import io.lettuce.core.codec.StringCodec
import nbcp.base.extend.AsInt
import nbcp.base.extend.*
import nbcp.base.utils.SpringUtil
import nbcp.db.redis.RedisConfig
import java.io.Serializable
import java.nio.ByteBuffer

/**
 * Created by yuxh on 2018/6/7
 */

class RedisBlobProxy(
        collectionName: String,
        dbOffset: Int = 0,
        var defaultCacheSeconds: Int = 0): BaseRedisVarKeyProxy(dbOffset,collectionName) {


    fun get(key: String): Serializable? {
        var cacheKey = arrayOf(collectionName, key).filter { it.isNotEmpty() }.joinToString(":")
        var ret = redis.byteArrayCommand(dbOffset){ it.get(cacheKey) }
        if (ret == null) return null
        return ret.ToSerializableObject()
    }


    fun set(key: String, value: Serializable, cacheSeconds: Int = 0) {
        var cacheKey = arrayOf(collectionName, key).filter { it.isNotEmpty() }.joinToString(":")

        if (cacheSeconds <= 0) {
            redis.byteArrayCommand(dbOffset){ it.set(cacheKey, value.ToSerializableByteArray())}
        } else {
            redis.byteArrayCommand(dbOffset){ it.setex(cacheKey, cacheSeconds.toLong(), value.ToSerializableByteArray())}
        }
    }
}

